package cn.zxy.controller;

import cn.zxy.exception.BizException;
import cn.zxy.model.Good;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;
import java.util.Set;

//@Controller
public class GoodController {

    //异常信息
    @GetMapping("/gooderr")
    @ResponseBody
    public Good gooderr(Good good){
        if (good.getNum()==1){
            int i = 5/0;
        } else if (good.getNum()==2) {
            String name=null;
            name.equals("临时");
        } else if (good.getNum()==3) {
            throw new BizException(306,"突然出错了，你自己看着办");
        } else if (good.getNum()==4) {
            throw new BizException(418,"调用错误，请检查接口");
        }
        return good;
    }

    @PostMapping("/good")
    public ModelAndView good(@RequestBody Good good){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg",
                "商品名称"+good.getName()+
                "商品价格"+good.getPrice()+
                "商品数量"+good.getNum());
        mv.setViewName("good");
        return mv;
    }

//    @GetMapping("/good")
//    @ResponseBody
//    public Good goods(){
//        Good g = new Good();
//        g.setName("黄瓜");
//        g.setPrice(20);
//        g.setNum(30);
//        return g;
//    }

    @GetMapping("/goods")
    public Good goods2(){
        Good g = new Good();
        g.setName("黄瓜");
        g.setPrice(20);
        g.setNum(30);
        return g;
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public Good save(@RequestBody Good good){
        System.out.println(good.toString());
        return good;
    }

    @RequestMapping(value = "/save2",method = RequestMethod.POST)
    @ResponseBody
    public Map maps(@RequestBody Map map){
        //第一种遍历方式 根据键值对
//        Set set = map.entrySet();
//        Set<Map.Entry<String, Object>> set = map.entrySet();
//
//        for (Map.Entry<String, Object> entry : set){
//            String key = entry.getKey();
//            Object value = entry.getValue();
//            System.out.println(key+"=="+value);
//        }

        //set.iterator()
//        Iterator<Map.Entry<String, Object>> iterator = set.iterator();
//        while (iterator.hasNext()){
//            Map.Entry<String, Object> next = iterator.next();
//            String key = next.getKey();
//            Object value = next.getValue();
//            System.out.println(key+"=="+value);
//        }


        //第二种方式 根据key遍历
        Set<String> set = map.keySet();
        for (String key : set){
            Object value = map.get(key);
            System.out.println(key+"=="+value);
        }

        //通过value lambda

//        map.forEach((key,value)->{
//            if (key!=null){
//                System.out.println(key+"=="+value);
//            }
//        });
        return map;
    }

}
